<?php

/**
 * +----------------------------------------------------------------------
 * | 阿里云短信服务
 * | https://api.aliyun.com/api-tools/sdk/Dysmsapi?version=2017-05-25&language=php-tea&tab=primer-doc
 * |
 * | composer require alibabacloud/dysmsapi-20170525 2.0.24
 * +----------------------------------------------------------------------
 *                                            ...     .............
 *                                          ..   .:!o&*&&&&&ooooo&; .
 *                                        ..  .!*%*o!;.
 *                                      ..  !*%*!.      ...
 *                                     .  ;$$!.   .....
 *                          ........... .*#&   ...
 *                                     :$$: ...
 *                          .;;;;;;;:::#%      ...
 *                        . *@ooooo&&&#@***&&;.   .
 *                        . *@       .@%.::;&%$*!. . .
 *          ................!@;......$@:      :@@$.
 *                          .@!   ..!@&.:::::::*@@*.:..............
 *        . :!!!!!!!!!!ooooo&@$*%%%*#@&*&&&&&&&*@@$&&&oooooooooooo.
 *        . :!!!!!!!!;;!;;:::@#;::.;@*         *@@o
 *                           @$    &@!.....  .*@@&................
 *          ................:@* .  ##.     .o#@%;
 *                        . &@%..:;@$:;!o&*$#*;  ..
 *                        . ;@@#$$$@#**&o!;:   ..
 *                           :;:: !@;        ..
 *                               ;@*........
 *                       ....   !@* ..
 *                 ......    .!%$! ..     | AUTHOR: dfer
 *         ......        .;o*%*!  .       | EMAIL: df_business@qq.com
 *                .:;;o&***o;.   .        | QQ: 3504725309
 *        .;;!o&****&&o;:.    ..          | WEBSITE: http://www.dfer.site
 * +----------------------------------------------------------------------
 *
 */

namespace plugins\dfer_thinkcmf_tools\lib;

use Dfer\Tools\TpCommon;

use AlibabaCloud\SDK\Dysmsapi\V20170525\Dysmsapi;
use Exception;
use AlibabaCloud\Tea\Exception\{TeaError, TeaUnableRetryError};
use AlibabaCloud\Tea\Utils\Utils;
use Darabonba\OpenApi\Models\Config;
use AlibabaCloud\SDK\Dysmsapi\V20170525\Models\SendSmsRequest;
use AlibabaCloud\Tea\Utils\Utils\RuntimeOptions;


class Sms extends TpCommon
{
    protected $error;
    protected $accessKeyId;
    protected $accessKeySecret;

    public function __construct($accessKeyId, $accessKeySecret)
    {
        $this->accessKeyId = !empty($accessKeyId) ? $accessKeyId : '';
        $this->accessKeySecret = !empty($accessKeySecret) ? $accessKeySecret : '';
    }

    public function getError()
    {
        return $this->error;
    }

    /**
     * 使用AK&SK初始化账号Client
     * @return Dysmsapi Client
     */
    public function createClient()
    {
        // 工程代码泄露可能会导致 AccessKey 泄露，并威胁账号下所有资源的安全性。以下代码示例仅供参考。
        // 建议使用更安全的 STS 方式，更多鉴权访问方式请参见：https://help.aliyun.com/document_detail/311677.html。
        $config = new Config([
            // 必填，请确保代码运行环境设置了环境变量 ALIBABA_CLOUD_ACCESS_KEY_ID。
            "accessKeyId" => $this->accessKeyId,
            // 必填，请确保代码运行环境设置了环境变量 ALIBABA_CLOUD_ACCESS_KEY_SECRET。
            "accessKeySecret" => $this->accessKeySecret
        ]);
        // Endpoint 请参考 https://api.aliyun.com/product/Dysmsapi
        $config->endpoint = "dysmsapi.aliyuncs.com";
        return new Dysmsapi($config);
    }

    /**
     * 发送短信
     */
    public function sendSms($params = array())
    {

        $result = $this->validate($params, 'plugins\dfer_thinkcmf_tools\validate\SmsValidate');

        if ($result !== true) {
            $this->error = $result;
            return false;
        }

        $client = $this->createClient();
        if (!empty($params["TemplateParam"]) && is_array($params["TemplateParam"])) {
            $params["TemplateParam"] = json_encode($params["TemplateParam"], true);
            // $params["TemplateParam"] =  "{\"code\":\"1234\"}";
        }

        $sendSmsRequest = new SendSmsRequest([
            "phoneNumbers" => $params['PhoneNumbers'],
            "signName" => $params['SignName'],
            "templateCode" => $params['TemplateCode'],
            "templateParam" => $params['TemplateParam']
            // "templateParam" => "{\"code\":\"1234\"}"

        ]);
        try {
            // 复制代码运行请自行打印 API 的返回值
            $response = $client->sendSmsWithOptions($sendSmsRequest, new RuntimeOptions(['ignoreSSL' => true]));
            // var_dump($response->toMap());
            return true;
        } catch (Exception $error) {
            if (!($error instanceof TeaError)) {
                $error = new TeaError([], $error->getMessage(), $error->getCode(), $error);
            }
            // var_dump($error);
            $this->error = $error->message . PHP_EOL . ($error->data["Recommend"] ?? '');
            Utils::assertAsString($error->message);
            return false;
        }
    }
}
